<?php

namespace app\apiadmin\controller\liveManager;

use app\apiadmin\service\liveManager\LiveManagerService;
use app\apiadmin\service\statics\LiveRecoderService;
use app\apiadmin\service\statics\LiveUserStaticsService;
use app\apiadmin\service\TCSS\TImService;
use app\common\controller\BaseController;
use app\common\utils\Res;
use think\facade\Db;
use think\facade\Log;

/**
 * 腾讯云直播管理
 *
 */
class TIm extends BaseController
{
    public function makeUserSign()
    {
        $param = $this->request->post();
        if (empty($param["userId"])) {

            return Res::error("userId不能为空");
        }
        $tim = new TImService($param["userId"]);
        $sign = $tim->generateSign($param["userId"]);
        return Res::ok($sign);
    }

    public function SendChartCommand()
    {
        $param = $this->request->post();
        if (empty($param["chartId"])) {
            return Res::error("chartId不能为空");
        }

        if (empty($param["command"])) {
            return Res::error("command不能为空");
        }
        $tim = new TImService("administrator");
        $ret = $tim->message_system_notify_send_to_group($param["chartId"], $param["command"]);

        $liveReocde = new LiveRecoderService();
        $liveReocde->RecodeChartMessage($param["chartId"], $param["command"]);

        if ($ret === true) {
            return Res::ok("发送成功");
        } else {
            return Res::error($ret);
        }

    }

    public function ImCallBack()
    {
        // 写入文件
        Log::channel("imInfo")->info("imInfo:" . json_encode($this->request->post()));
        $tim = new TImService("administrator");

        $params = $this->request->post();
        $CallbackCommand = $params["CallbackCommand"];
        $group_id = $params["GroupId"]; // 群ID
        LiveManagerService::getLiveIdByGroupId($group_id);

        $isIllegal = 0; // 是否违规
        $isSilence = 0; // 是否禁言
        $isHide = 0; // 是否隐藏处理
        $isDigitMan = 0; // 数字人/评论组是否隐藏

        // --群组消息发送异常回调
        if ($CallbackCommand == "Group.CallbackSendMsgException") {
            $From_Account = $params["From_Account"];
            $cloud = json_decode($params["CloudCustomData"], true);
            $content = "";
            $msgBody = $params["MsgBody"];
            if ($msgBody[0]["MsgType"] == "TIMTextElem") {
                $content = $msgBody[0]["MsgContent"]["Text"];
            }
            if (empty($content)) {
                if ($params['ErrorCode'] === 10017) {
                    // 禁言中，发送自定义消息，用于飘字  type=5
                    $custom = $msgBody[0]["MsgContent"];
                    $command = [
                        "command" => $custom['Desc'],
                        "nick" => $custom['Data'],
                    ];
                    $tim->message_system_notify_send_to_group($group_id, json_encode($command));
                }
                return false;
            }
            $cloud['group_id'] = $group_id;
            if ($params['ErrorCode'] === 10016) {
                $isIllegal = 1; // 违禁词过滤
                if ($cloud['type'] == 4) {
                    $cloud['type'] = 47;
                } else {
                    $cloud['type'] = 7;
                }
                $tim->message_temporary_send_to_administrator($content, $From_Account, json_encode($cloud));
            }
            if ($params['ErrorCode'] === 10017) {
                $isSilence = 1; // 禁言
                $cloud['type'] = 6;
                $tim->message_temporary_send_to_administrator($content, $From_Account, json_encode($cloud));
            }

            // 写入 数据库和redis
            $item = [
                "GroupId" => $group_id,
                "From_Account" => $From_Account,
                "Operator_Account" => $params["Operator_Account"],
                "ErrorCode" => $params["ErrorCode"],
                "MsgBody" => $content,
                "EventTime" => $params["EventTime"],
                "CloudCustomData" => json_encode($cloud),
                "no" => $cloud['no'],
                "type" => $cloud['type'],
                "random_id" => $params["Random"],
                "is_illegal" => $isIllegal,
                "is_silence" => $isSilence,
                "is_hide" => $isHide,
                "is_digit_man" => $isDigitMan,
            ];
            // 写入数据
            $id = Db::name("siyu_im_group_msg")->insert($item, true);
            $item['id'] = $id;
            $tim->redis_add_online_msg($group_id, $item, $cloud['type']);
            Log::channel("imInfo")->info("ImCallback:CallbackSendMsgException:ret");

            $liveId = LiveManagerService::getLiveIdByGroupId($group_id);
            $luss = new LiveUserStaticsService($liveId);
            $luss->OnLiveUserSendMsg($From_Account, $params);

        }
        // --群组消息发送成功之后
        if ($CallbackCommand == "Group.CallbackAfterSendMsg") {
            $From_Account = $params["From_Account"];
            $CloudCustomData = $params["CloudCustomData"];
            $cloud = json_decode($CloudCustomData, true);
            $content = "";
            $msgBody = $params["MsgBody"];
            if ($msgBody[0]["MsgType"] == "TIMTextElem") {
                $content = $msgBody[0]["MsgContent"]["Text"];
            }
            if (empty($content)) {
                return false;
            }
            if ($cloud['type'] == 3 || $cloud['type'] == 4) {
                $isDigitMan = 1;
            }
            if ($cloud['type'] == 6) {
                //禁言用户单聊助教
                $isSilence = 1;
            }
            if ($cloud['type'] == 7) {
                //违禁词消息
                $isIllegal = 1;
            }
            // 写入 数据库和redis
            $item = [
                "GroupId" => $group_id,
                "From_Account" => $From_Account,
                "Operator_Account" => $params["Operator_Account"],
                "MsgSeq" => $params["MsgSeq"],
                "MsgTime" => $params["MsgTime"],
                "MsgBody" => $content,
                "EventTime" => $params["EventTime"],
                "CloudCustomData" => json_encode($cloud),
                "no" => $cloud['no'],
                "type" => $cloud['type'],
                "random_id" => $params["Random"],
                "is_illegal" => $isIllegal,
                "is_silence" => $isSilence,
                "is_hide" => $isHide,
                "is_digit_man" => $isDigitMan,
            ];
            Log::channel("imInfo")->info("ImCallback:CallbackAfterSendMsg:item " . json_encode($item));
            // 写入数据
            $id = Db::name("siyu_im_group_msg")->insert($item, true);
            $item['id'] = $id;
            $tim->redis_add_online_msg($group_id, $item, $cloud['type']);
            if ($isIllegal) {
                $tim->redis_add_illegal_msg($group_id, $item);
            }
            //if ($isSilence) {
            //    $tim->redis_set_silence_msg($group_id, $item);
            //}
            Log::channel("imInfo")->info("ImCallback:CallbackAfterSendMsg:ret " . $id);

            $liveId = LiveManagerService::getLiveIdByGroupId($group_id);
            Log::channel("imInfo")->info("ImCallback:CallbackSendMsgException:ImCallBack:---" . $liveId . '---' . $group_id);
            $luss = new LiveUserStaticsService($liveId);
            $luss->OnLiveUserSendMsg($From_Account, $params);

        }

        /**
         * 群组在线状态回调
         * 可能触发场景
         * App 用户进入直播群之后，未正常退群，并且网络中断超过20s。
         * App 用户进入直播群之后，未正常退群，网络中断超过20s，重新上线。
         * App 用户首次进入直播群（一个用户多个App终端进入一个直播群，仅回调第一次）。
         * App 用户最后一次主动退出直播群。
         * 回调发生时机
         * 用户进入直播群之后，因网络中断等原因导致心跳请求超时触发 Offline 事件；当超时20s重新上线时触发 Online 事件。若同一个用户使用多台设备登录，并且多台设备同时加入到同一个直播间时，只有当所有设备同时掉线才会触发 Offline 事件，当任一设备恢复上线时触发 Online 事件（多台设备恢复时仅触发一次 Online 事件）。
         *
         * */
        if ($CallbackCommand == "Group.CallbackOnMemberStateChange") {
            $group_id = $params["GroupId"];
            $EventType = $params["EventType"];
            Log::channel("imInfo")->info("ImCallback:CallbackOnMemberStateChange:" . $EventType);

            $MemberList = [];
            array_walk($params["MemberList"], function ($item) use (&$MemberList) {
                $MemberList[] = $item["Member_Account"];
            });

            if ($EventType == "Offline") {
                // $tim->redis_remove_onlin_user($group_id, $MemberList);
                $group_id = $params["GroupId"];
                $ExitType = $params["EventCause"];

                $MemberList = [];
                array_walk($params["MemberList"], function ($item) use (&$MemberList) {
                    $MemberList[] = $item["Member_Account"];
                });
                $tim->redis_remove_onlin_user($group_id, $MemberList);

                $liveId = LiveManagerService::getLiveIdByGroupId($group_id);
                $luss = new LiveUserStaticsService($liveId);
                foreach ($MemberList as $key => $value) {
                    // $luss->OnLiveUserExit($value, json_encode($params));
                }
            }

            if ($EventType == "Online") {
                $tim->redis_add_online_user($group_id, $MemberList);
                // $group_id = $params["GroupId"];
                // $JoinType = $params["EventCause"];
                // Log::channel("imInfo")->info("ImCallback:CallbackAfterNewMemberJoin-Online:" . $JoinType);

                // $MemberList = [];
                // array_walk($params["MemberList"], function ($item) use (&$MemberList) {
                //     $MemberList[] = $item["Member_Account"];
                // });

                // $tim->redis_add_online_user($group_id, $MemberList);

                // $liveId = LiveManagerService::getLiveIdByGroupId($group_id);
                // $luss = new LiveUserStaticsService($liveId);
                // foreach ($MemberList as $key => $value) {
                //     $luss->OnLiveUserEnter($value, $params);
                // }
            }

        }

        //新成员入群回调
        if ($CallbackCommand == "Group.CallbackAfterNewMemberJoin") {
            $group_id = $params["GroupId"];
            $JoinType = $params["JoinType"];
            Log::channel("imInfo")->info("ImCallback:CallbackAfterNewMemberJoin:" . $JoinType);

            $MemberList = [];
            array_walk($params["NewMemberList"], function ($item) use (&$MemberList) {
                $MemberList[] = $item["Member_Account"];
            });

            $tim->redis_add_online_user($group_id, $MemberList);

            $liveId = LiveManagerService::getLiveIdByGroupId($group_id);
            $luss = new LiveUserStaticsService($liveId);
            foreach ($MemberList as $key => $value) {
                // $luss->OnLiveUserEnter($value, $params);
            }

        }

        //成员退群回调
        if ($CallbackCommand == "Group.CallbackAfterMemberExit") {
            $group_id = $params["GroupId"];
            $ExitType = $params["ExitType"];
            Log::channel("imInfo")->info("ImCallback:CallbackAfterMemberExit:" . $ExitType);

            $MemberList = [];
            array_walk($params["ExitMemberList"], function ($item) use (&$MemberList) {
                $MemberList[] = $item["Member_Account"];
            });
            $tim->redis_remove_onlin_user($group_id, $MemberList);

            $liveId = LiveManagerService::getLiveIdByGroupId($group_id);
            $luss = new LiveUserStaticsService($liveId);
            foreach ($MemberList as $key => $value) {
                // $luss->OnLiveUserExit($value, $params);
            }

        }

        return Res::jsonResult([
            "ActionStatus" => "OK",
            "ErrorInfo" => "",
            "ErrorCode" => 0, //忽略回调结果
        ]);

    }

}
